#!M:/WinPython-64bit-3.4.4.3Qt5/python-3.4.4.amd64/python.exe
#coding=utf-8

print("Content-Type:text/html;Charset:UTF-8\n\n")

import cgi,cgitb
import base64,io,os
from PIL import Image
cgitb.enable()
fm=cgi.FieldStorage()
if fm['file']:
    filename=fm['filename'].value
    name,ext=os.path.splitext(filename)
    #print(name)
    thumbnailname="".join([name,'_thumbnail.jpg'])
    #print(thumbnailname)
    if not os.path.exists('images/'):
        os.mkdir('images')
    if not os.path.exists('thumbnails/'):
        os.mkdir('thumbnails')
    fp='images/{0:s}'.format(filename)
    tp='thumbnails/{0:s}'.format(thumbnailname)
    #print(tp)
    with open(fp,'wb') as image_file:
        head,body=fm['file'].value.split(',',1)
        bbody=base64.b64decode(body)
        o=io.BytesIO(bbody)
        image_file.write(o.read())
    try:
        image_hander=Image.open(fp)
        image_hander.thumbnail((100,100))
        image_hander.save(tp)
    except:
        pass
    else:
        print('Upload success!')
        
    
